/*!
 * jRaiser Module Development Kit
 * Module compiler (2013-01-15T15:21:29+0800)
 * http://jraiser.org/ | Released under MIT license
 */

var uglifyjs = require('uglify-js'), util = require('./lib/util');


// 去掉代码中的注释
// from http://lifesinger.github.com/lab/2011/remove-comments-safely/
function removeComments(code) {
	return code
		.replace(/^\s*\/\*[\s\S]*?\*\/\s*$/mg, '') 	// block comments
        .replace(/^\s*\/\/.*$/mg, '');				// line comments
}


util.extend(exports, {
	// 获取依赖模块
	parseDeps: function(code) {
		var pattern = /(?:^|[^.$])\brequire\s*\(\s*(["'])([^"'\s\)]+)\1\s*\)/g;
		var ret = [ ], match;

		code = removeComments(code);
		while ( match = pattern.exec(code) ) {
			if (match[2]) {
				ret.push(match[2]);
			}
		}

		ret = util.literalUnique(ret);

		return ret.length ? ret : null;
	},

	// 编译模块
	compile: function(content, allDeps, id) {
		// 保留版权信息
		var copyright = /^\/\*[\s\S]+?\*\//.test(content) ? RegExp.lastMatch + '\r\n' : '';

		var ret = uglifyjs(content);

		ret = ret.replace(/^(define\()(function\()/, function($0, $1, $2) {
			var params = [ ];
			if (id != null) {
				params.push( JSON.stringify(id) );
			}
			if (params.length || allDeps) {
				params.push( allDeps ? JSON.stringify(allDeps) : 'null' );
			}
			params.push($2);

			return $1 + params.join(',');
		});

		return copyright + ret;
	}
});